package com.googlecode.agscrum.controller.jsf.bean;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.googlecode.agscrum.model.entity.Product;
import com.googlecode.agscrum.model.entity.Team;
import com.googlecode.agscrum.model.service.Service;
import com.googlecode.agscrum.model.util.Criteria;
import com.googlecode.agscrum.model.util.Restrictions;

@Controller("productControllerBean")
@Scope("request")
@Configurable(autowire = Autowire.BY_NAME)
public class ProductControllerBean extends BaseControllerBean<Product, Long> {

	private Service<Product, Long> productService;

	public void setProductService(Service<Product, Long> productService) {
		this.productService = productService;
	}

	private Service<Team, Long> teamService;

	public void setTeamService(Service<Team, Long> teamService) {
		this.teamService = teamService;
	}

	private List<Team> teams;

	private List<Team> selectedTeams;

	@Override
	protected void reset() {
		teams = null;
		selectedTeams = null;
	}

	@Override
	protected Criteria getCriteria() {
		Criteria criteria = Criteria.getInstance("Product.searchQuery",
				Product.class);
		criteria.addAnd(Restrictions.ilike("l.name", true, getEntity()
				.getName(), true));
		return criteria;
	}

	@Override
	protected Service<Product, Long> getService() {
		return productService;
	}

	public void setSelectedTeams(List<Team> selectedTeams) {
		this.selectedTeams = selectedTeams;
	}

	public List<Team> getSelectedTeams() {
		return selectedTeams;
	}

	public void setTeams(List<Team> teams) {
		this.teams = teams;
	}

	@Override
	protected void beforeSave() {
		getEntity().changeTeams(selectedTeams);
		super.beforeSave();
	}

	@Override
	public String save() {
		return super.save();
	}

	@Override
	public void setEntity(Product entity) {
		if (entity != null && entity.getId() != null) {
			selectedTeams = entity.getTeams();
		}
		super.setEntity(entity);
	}

	public List<Team> getTeams() {
		teams = teamService.findAll();
		List<Team> filterTeams = new ArrayList<Team>();
		if (getEntity().getId() != null) {
			for (Team team : teams) {
				if (selectedTeams == null || !(selectedTeams.contains(team))) {
					filterTeams.add(team);
				}
			}
			teams = filterTeams;
		}
		return teams;
	}
}
